﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Truron.Purchase.Interface;
using Truron.Purchase.Api.Utility;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Truron.Purchase.Model;
using Newtonsoft.Json;
using Truron.Purchase.Utility;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using System.IO;
using Truron.Purchase.Api.Filter;

namespace Truron.Purchase.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class Purchase_FileInfoController : ControllerBase
    {
        private readonly IPurchase_FileInfoService _purchase_FileInfoService;
        private static string SvaeFileUrl = "";
        public Purchase_FileInfoController(IPurchase_FileInfoService Purchase_FileInfoService)
        {
            _purchase_FileInfoService = Purchase_FileInfoService;
            var Configuration = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 .AddJsonFile("appsettings.json", optional: true)
                 .Build();
            SvaeFileUrl = Configuration.GetSection("AppSettings:FileDir").Value;
        }
        public class UploadFileParam
        {
            public string GrpCode { get; set; }
            //public IFormFile file { get; set; }
        }
        public IActionResult UploadFile()
        {
            var files = Request.Form.Files;
            var GrpCode = Request.Form["GrpCode"].ToString();
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    int count = formFile.FileName.Split('.').Length;
                    string SourceName = "";
                    for(int i=0;i<count-1;i++)
                    {
                        if(i==0)
                        {
                            SourceName = formFile.FileName.Split('.')[i];
                        }
                        else
                        {
                            SourceName = SourceName+ "."+ formFile.FileName.Split('.')[i];
                        }
                    }
                    string fileExt = formFile.FileName.Split('.')[count - 1]; //文件扩展名，不含“.”
                    long fileSize = formFile.Length; //获得文件大小，以字节为单位
                    string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt;  //随机生成新的文件名
                    #region 文件夹不存在则创建
                    var filePath = SvaeFileUrl + "/upload/"+ DateTime.Now.ToString("yyyyMMdd");
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    #endregion
                    #region 文件不存在则新建
                    filePath = filePath + "/" + newFileName;
                    //showfilePath = "upload/" + newFileName;
                    //FileHelper.CreateFile(filePath);
                    #endregion
                    //把上传的图片复制到指定的文件中
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        formFile.CopyTo(stream);
                    }
                    //上传成功以后再把数据写入数据库
                    Purchase_FileInfo entity = new Purchase_FileInfo();
                    entity.GrpCode = GrpCode;
                    entity.SourceName = SourceName + "." + fileExt;
                    entity.FilePath = filePath;
                    entity.FileSuffix = fileExt;
                    entity.FileSize = CommonHelper.GetSize(fileSize);
                    entity.Sort = 0;
                    _purchase_FileInfoService.SaveFile(entity, userToken);

                }
            }
            //var grpcode = GrpCode.GrpCode;
            //FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0 }));
        }
        public class GetFileListParam
        {
            public string GrpCode { get; set; }
        }
        public IActionResult GetFileList(GetFileListParam param)
        {
            var list = _purchase_FileInfoService.GetFileList(param.GrpCode);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = list, code=0 }));
        }
        public class DeleteFileParam
        {
            public int FileId { get; set; }
        }
        public IActionResult DeleteFile(DeleteFileParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            _purchase_FileInfoService.DeleteFile(param.FileId, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() {code = 0 }));
        }
        public class DownLoadFileParam
        {
            public int FileId { get; set; }
        }
        [SkipActionFilter]
        [HttpPost]
        [AllowAnonymous]
        public IActionResult DownLoadFile()
        {
            var FileId = Request.Form["FileId"].ToString();
            var entity = _purchase_FileInfoService.GetFileEntity(Convert.ToInt32(FileId));
           

            //var fileInfo = _purchase_FileInfoService.DownFile(param.FileId);
            //return File(fileInfo.file, fileInfo.type, fileInfo.filename);
            return File(new FileStream(entity.FilePath, FileMode.Open), "application/octet-stream", entity.SourceName);
        }
    }
}
